//package com.example.mcdonaldapplication.activity
//
//import android.Manifest
//import android.Manifest.permission
//import android.content.pm.PackageManager
//import android.location.LocationListener
//import android.os.Build
//import android.os.Bundle
//import android.widget.Toast
//import androidx.annotation.RequiresApi
//import androidx.appcompat.app.AppCompatActivity
//import androidx.core.app.ActivityCompat
//import androidx.core.content.ContextCompat
//import com.baidu.location.BDAbstractLocationListener
//import com.baidu.location.BDLocation
//import com.baidu.location.LocationClient
//import com.baidu.location.LocationClientOption
//import com.baidu.mapapi.map.BaiduMap
//import com.baidu.mapapi.map.BaiduMapOptions
//import com.baidu.mapapi.map.MapView
//import com.baidu.mapapi.map.MyLocationData
//import com.example.mcdonaldapplication.databinding.ActivityMapBinding
//
//
//class MapActivity : AppCompatActivity() {
//
//    private lateinit var binding: ActivityMapBinding
//    private lateinit var mapView: MapView
//    private lateinit var mBaiduMap: BaiduMap
//    private lateinit var mLocationClient: LocationClient
//    private lateinit var myLocationListener: MyLocationListener
//
//    @RequiresApi(Build.VERSION_CODES.M)
//    override fun onCreate(savedInstanceState: Bundle?) {
//        super.onCreate(savedInstanceState)
////        setContentView(R.layout.activity_map)
//        binding = ActivityMapBinding.inflate(layoutInflater)
//
//        val permission = Manifest.permission.ACCESS_FINE_LOCATION
////        val permission = Manifest.permission.ACCESS_COARSE_LOCATION
//
//        val checkSelfPermission = ActivityCompat.checkSelfPermission(this,permission)
////        if (ContextCompat.checkSelfPermission(this, permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) {
////            Toast.makeText(this,"请授权",Toast.LENGTH_SHORT).show()
////        }
////        val permissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
////        requestPermissions(permissions,2)
//
//        if (checkSelfPermission  == PackageManager.PERMISSION_GRANTED) {
//            //已经获取到权限  获取用户媒体资源
//            Toast.makeText(this,"已经获取权限",Toast.LENGTH_SHORT).show()
//        }else{
//            val permissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
//            requestPermissions(permissions,8)
//        }
//        val options = BaiduMapOptions()
////        options.mapType(BaiduMap.MAP_TYPE_SATELLITE)
//        options.mapType(BaiduMap.MAP_TYPE_NORMAL)
//        mapView = MapView(this,options)
//        mBaiduMap = mapView.map
//        mBaiduMap.isMyLocationEnabled = true
//
//        mLocationClient = LocationClient(this)
//
////通过LocationClientOption设置LocationClient相关参数
//
////通过LocationClientOption设置LocationClient相关参数
//        val option = LocationClientOption()
//        option.isOpenGps = true // 打开gps
//
//        option.setCoorType("bd09ll") // 设置坐标类型
//
//        option.setScanSpan(1000)
//
////设置locationClientOption
//
////设置locationClientOption
//        mLocationClient.locOption = option
//
////注册LocationListener监听器
//
////注册LocationListener监听器
//        myLocationListener = MyLocationListener()
//        mLocationClient.registerLocationListener(myLocationListener)
////开启地图定位图层
////开启地图定位图层
//        mLocationClient.start()
//        setContentView(mapView)
//
//    }
//
//    /*override fun onRequestPermissionsResult(
//        requestCode: Int,
//        permissions: Array<out String>,
//        grantResults: IntArray
//    ) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//        if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
//
//        }
//    }*/
//
//    inner class MyLocationListener: BDAbstractLocationListener() {
//        override fun onReceiveLocation(location: BDLocation?) {
//            //mapView 销毁后不在处理新接收的位置
//            if (location == null || mapView == null) {
//                return
//            }
//            val locData = MyLocationData.Builder()
//                .accuracy(location.radius) // 此处设置开发者获取到的方向信息，顺时针0-360
//                .direction(location.direction).latitude(location.latitude)
//                .longitude(location.longitude).build()
//            mBaiduMap.setMyLocationData(locData)
//        }
//    }
//
//    override fun onResume() {
//        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
//        mapView.onResume()
//        super.onResume()
//    }
//
//    override fun onPause() {
//        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
//        mapView.onPause()
//        super.onPause()
//    }
//
//    override fun onDestroy() {
//        mLocationClient.stop();
//        mBaiduMap.isMyLocationEnabled = false;
//        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
//        mapView.onDestroy()
//        super.onDestroy()
//    }
//
//
//}
//
//private fun BaiduMap.mapType(mapTypeNormal: Int) {
//
//}
//
//


package com.example.mcdonaldapplication.activity

import android.Manifest
import android.content.pm.PackageManager
//import android.support.v7.app.AppCompatActivity
import android.os.Bundle
//import android.support.v4.app.ActivityCompat
//import android.support.v4.content.ContextCompat
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.baidu.location.BDLocation
import com.baidu.location.BDLocationListener
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.SDKInitializer
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.MapStatusUpdateFactory
import com.baidu.mapapi.map.MapView
import com.baidu.mapapi.map.MyLocationData
import com.baidu.mapapi.model.LatLng
import com.example.mcdonaldapplication.R


class MapActivity : AppCompatActivity() {

    var mLocationClient: LocationClient? = null
    var positionText: TextView? = null
    var mapView: MapView? = null
    var baiduMap: BaiduMap? = null
    var isFirstLocate = true


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mLocationClient = LocationClient(applicationContext)
        mLocationClient?.registerLocationListener(MyLocationListener())
        SDKInitializer.initialize(applicationContext)
        supportActionBar?.hide()
        setContentView(R.layout.activity_map)

        positionText = findViewById<TextView>(R.id.position_text_view)
        mapView = findViewById<MapView>(R.id.bmapView)
        baiduMap = mapView?.map
        baiduMap?.isMyLocationEnabled = true

        var permissionList = ArrayList<String>()
        if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION)
        }


        if(permissionList.isNotEmpty()) {
            val permissions = permissionList.toArray(arrayOfNulls<String>(permissionList.size))
            ActivityCompat.requestPermissions(this,permissions,1)
        }else {
            requestLocation()
        }
    }


    private fun initLocation() {
        var option = LocationClientOption()
//        option.locationMode = LocationClientOption.LocationMode.Device_Sensors
        option.scanSpan = 5000
        option.setIsNeedAddress(true)
        mLocationClient?.locOption = option
    }


    fun navigateTo(location: BDLocation) {
        if(isFirstLocate) {
            var ll = LatLng(location.latitude,location.longitude)
            var update = MapStatusUpdateFactory.newLatLng(ll)
            baiduMap?.animateMapStatus(update)
            update = MapStatusUpdateFactory.zoomTo(16f)
            baiduMap?.animateMapStatus(update)
            isFirstLocate = false
        }

        var locationBuilder = MyLocationData.Builder()
        locationBuilder.latitude(location.latitude)
        locationBuilder.longitude(location.longitude)
        var locationData = locationBuilder.build()
        baiduMap?.setMyLocationData(locationData)
    }


    private fun requestLocation() {
        initLocation()
        mLocationClient?.start()
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when(requestCode) {
            1 -> {
                if(grantResults.isNotEmpty()) {
                    for(result in grantResults) {
                        if(result != PackageManager.PERMISSION_GRANTED) {
                            Toast.makeText(this,"必须同意所有权限才能使用本程序",Toast.LENGTH_SHORT).show()
                            finish()
                            return
                        }
                    }

                    requestLocation()
                }else {
                    Toast.makeText(this,"发生未知错误",Toast.LENGTH_SHORT).show()
                    finish()
                }
            }

            else -> {

            }
        }
    }


    override fun onResume() {
        super.onResume()
        mapView?.onResume()
    }

    override fun onPause() {
        super.onPause()
        mapView?.onPause()
    }


    override fun onDestroy() {
        super.onDestroy()
        mLocationClient?.stop()
        mapView?.onDestroy()
        baiduMap?.isMyLocationEnabled = false
    }


    inner class MyLocationListener: BDLocationListener{
        override fun onReceiveLocation(location: BDLocation?) {
//            runOnUiThread(object: Runnable {
//                override fun run() {
//
//                    var currentPosition = StringBuilder()
//                    currentPosition.append("维度: ").append(location?.latitude).append("\n")
//                    currentPosition.append("经度: ").append(location?.longitude).append("\n")
//                    currentPosition.append("定位方式: ")
//
//                    currentPosition.append("国家: ").append(location?.country).append("\n")
//                    currentPosition.append("省: ").append(location?.province).append("\n")
//                    currentPosition.append("市: ").append(location?.city).append("\n")
//                    currentPosition.append("区: ").append(location?.district).append("\n")
//                    currentPosition.append("街道: ").append(location?.street).append("\n")
//
//
//                    if(location?.locType == BDLocation.TypeGpsLocation) {
//                        currentPosition.append("GPS")
//                    }else if(location?.locType == BDLocation.TypeNetWorkLocation) {
//                        currentPosition.append("网络")
//                    }
//
//                    positionText?.setText(currentPosition)
//                }
//            })


            if(location?.locType == BDLocation.TypeGpsLocation || location?.locType == BDLocation.TypeNetWorkLocation) {
                navigateTo(location!!)
            }
        }
    }
}

